package com.eduhzy.ttw.work.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.eduhzy.ttw.commonres.activity.PicturePlayAudioActivity;
import com.eduhzy.ttw.commonres.activity.VideoPlayActivity;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonres.view.AutoConstraintLayout;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.decoration.GridSpacingItemDecoration;
import com.eduhzy.ttw.commonsdk.utils.MediaFile;
import com.eduhzy.ttw.work.R;
import com.eduhzy.ttw.work.R2;
import com.eduhzy.ttw.work.di.component.DaggerCheckWorkComponent;
import com.eduhzy.ttw.work.di.module.CheckWorkModule;
import com.eduhzy.ttw.work.mvp.contract.CheckWorkContract;
import com.eduhzy.ttw.work.mvp.model.entity.WorkCheckDetailData;
import com.eduhzy.ttw.work.mvp.model.entity.WorkDetailData;
import com.eduhzy.ttw.work.mvp.presenter.CheckWorkPresenter;
import com.eduhzy.ttw.work.mvp.ui.adapter.WorkFileAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DoubleUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-12-3 17:45:21
 */
@Route(path = RouterHub.WORK_CHECKWORKACTIVITY)
public class CheckWorkActivity extends BaseActivity<CheckWorkPresenter> implements CheckWorkContract.View {
    @Autowired(name = Constants.PARCELABLE_DATA)
    WorkDetailData.HomeworkClassListBean mBean;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;
    @BindView(R2.id.bottom_progressbar)
    ProgressBar mBottomProgressbar;
    @BindView(R2.id.tv_name)
    TextView mTvName;
    @BindView(R2.id.tv_time)
    TextView mTvTime;
    @BindView(R2.id.tv_content)
    TextView mTvContent;
    @BindView(R2.id.rv_list2)
    RecyclerView mRvList2;
    @BindView(R2.id.layout_title)
    AutoConstraintLayout mLayoutTitle;
    @BindView(R2.id.tv_label)
    TextView mTvLabel;
    @BindView(R2.id.btn_score1)
    QMUIRoundButton mBtnScore1;
    @BindView(R2.id.btn_score2)
    QMUIRoundButton mBtnScore2;
    @BindView(R2.id.btn_score3)
    QMUIRoundButton mBtnScore3;
    @BindView(R2.id.btn_score4)
    QMUIRoundButton mBtnScore4;
    @BindView(R2.id.btn_score5)
    QMUIRoundButton mBtnScore5;
    @BindView(R2.id.tv_score1)
    TextView mTvScore1;
    @BindView(R2.id.tv_score2)
    TextView mTvScore2;
    @BindView(R2.id.tv_score3)
    TextView mTvScore3;
    @BindView(R2.id.tv_score4)
    TextView mTvScore4;
    @BindView(R2.id.tv_score5)
    TextView mTvScore5;
    @BindView(R2.id.tv_label2)
    TextView mTvLabel2;
    @BindView(R2.id.et_comment)
    EditText mEtComment;
    @BindView(R2.id.btn_submit)
    QMUIRoundButton mBtnSubmit;
    @BindView(R2.id.btn_pre)
    QMUIRoundButton mBtnPre;
    @BindView(R2.id.btn_next)
    QMUIRoundButton mBtnNext;

    @Inject
    WorkFileAdapter mAdapterStudent;
    @Inject
    RecyclerView.LayoutManager mManager;
    private WorkCheckDetailData mData;
    private TextView tv_score;
    private QMUIRoundButton btn_score;
    private int btn_id;
    private int score;
    @Autowired(name = Constants.ROUTER_INTEGER)
    int type;
    List<QMUIRoundButton> btns = new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerCheckWorkComponent
                .builder()
                .appComponent(appComponent)
                .checkWorkModule(new CheckWorkModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        MobclickAgent.onEvent(getActivity(),"ttw_work_check");
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.work_activity_check_work;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        btns.add(mBtnScore1);
        btns.add(mBtnScore2);
        btns.add(mBtnScore3);
        btns.add(mBtnScore4);
        btns.add(mBtnScore5);
        if (type == 1) {
            mBtnNext.setVisibility(View.GONE);
            mBtnPre.setVisibility(View.GONE);
            mBtnSubmit.setVisibility(View.VISIBLE);
            mBottomProgressbar.setVisibility(View.VISIBLE);
        } else {
            mBottomProgressbar.setVisibility(View.GONE);
            mBtnNext.setVisibility(View.VISIBLE);
            mBtnPre.setVisibility(View.VISIBLE);
            mBtnSubmit.setVisibility(View.GONE);
        }
        mEmptyView.show(true);
        getData();
        mBtnScore4.performClick();
    }

    private void getData() {
        mPresenter.workRecordDetail4Teacher(mBean.getWorkId(), mBean.getClassId(), mBean.getStudentId());
    }

    @Override
    public void showLoading() {
        mEmptyView.show(true);
    }

    @Override
    public void hideLoading() {
        mEmptyView.hide();
    }


    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void update(WorkCheckDetailData data) {
        if (type == 1)
            mBottomProgressbar.setProgress((data.getCheckNum() * 100) / data.getSubmitNum());
        this.mData = data;
        if (ObjectUtils.isNotEmpty(data.getComment())) {
            mEtComment.setText(data.getComment());
        }
        if (data.getScore() > 0) {
            btns.get(data.getScore() - 1).performClick();
        }
        mTvName.setText(data.getUserRealName());
        mTvContent.setText(data.getWorkContent());
        mTvTime.setText(TimeUtils.millis2String(data.getEndTime(), new SimpleDateFormat("MM月dd日 HH:mm")));
        mRvList2.setLayoutManager(mManager);
        GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(4, RxUtil.getAutoHeight(this, 15), false);
        mRvList2.addItemDecoration(decoration);
        mRvList2.setAdapter(mAdapterStudent);
        mAdapterStudent.getData().clear();
        List<LocalMedia> imgs = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(data.getImageList())) {
            mAdapterStudent.addData(data.getImageList());
            for (WorkDetailData.FileListBean bean : data.getImageList()) {
                LocalMedia media = new LocalMedia();
                media.setPath(bean.getUrl());
                imgs.add(media);
            }
        }
        if (ObjectUtils.isNotEmpty(data.getVideoList())) {
            mAdapterStudent.addData(data.getVideoList());
        }
        if (ObjectUtils.isNotEmpty(data.getAudioList())) {
            mAdapterStudent.addData(data.getAudioList());
        }
        mAdapterStudent.setOnItemClickListener((adapter, view, position) -> {
            WorkDetailData.FileListBean item = mAdapterStudent.getData().get(position);
            String mimeTypeForFile = MediaFile.getMimeTypeForFile(item.getName());
            int fileTypeForMimeType = MediaFile.getFileTypeForMimeType(mimeTypeForFile);

            if (MediaFile.isAudioFileType(fileTypeForMimeType)) {
                if (ObjectUtils.isEmpty(item.getUrl())) {
                    showMessage("音频转换中，请稍后");
                    getData();
                    return;
                }
                if (!DoubleUtils.isFastDoubleClick()) {
                    Intent intent = new Intent(this.getActivity(), PicturePlayAudioActivity.class);
                    intent.putExtra("audio_path", item.getUrl());
                    this.getActivity().startActivity(intent);
                    this.getActivity().overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                }
            } else if (MediaFile.isVideoFileType(fileTypeForMimeType)) {
                if (ObjectUtils.isEmpty(item.getUrl())) {
                    showMessage("视频转换中，请稍后");
                    getData();
                    return;
                }
                if (!DoubleUtils.isFastDoubleClick()) {
                    Intent intent = new Intent(this.getActivity(), VideoPlayActivity.class);
                    intent.putExtra(Constants.ROUTER_STRING, item.getUrl());
                    intent.putExtra(Constants.ROUTER_IMG, item.getPreimage());
                    this.getActivity().startActivity(intent);
                    this.getActivity().overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                }

            } else if (MediaFile.isImageFileType(fileTypeForMimeType)) {

                PictureSelector.create(getActivity()).themeStyle(R.style.picture_default_style).openExternalPreview(data.getImageList().indexOf(item), imgs);
            }
        });
    }

    @OnClick({R2.id.btn_pre, R2.id.btn_next, R2.id.btn_submit})
    public void onViewClicked2(View view) {
        int i = view.getId();
        if (RxUtil.showEditTip(this, mEtComment, "请输入评语")) {
            return;
        }
        if (i == R.id.btn_submit) {
            mPresenter.checkWorkRecord(mBean.getWorkId(), mBean.getClassId(), mData.getUserId(), mEtComment.getText().toString(), score, type);
        } else if (i == R.id.btn_pre) {
            mPresenter.checkWorkRecord(mBean.getWorkId(), mBean.getClassId(), mData.getUserId(), mEtComment.getText().toString(), score, 3);
        } else if (i == R.id.btn_next) {
            mPresenter.checkWorkRecord(mBean.getWorkId(), mBean.getClassId(), mData.getUserId(), mEtComment.getText().toString(), score, 2);
        }
    }

    @OnClick({R2.id.btn_score1, R2.id.btn_score2, R2.id.btn_score3, R2.id.btn_score4, R2.id.btn_score5})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (btn_id == i) {
            return;
        } else {
            btn_id = i;
            if (ObjectUtils.isNotEmpty(tv_score)) {
                tv_score.setSelected(false);
            }
            if (ObjectUtils.isNotEmpty(btn_score)) {
                btn_score.setSelected(false);
            }
        }
        if (i == R.id.btn_score1) {
            score = 1;
            tv_score = mTvScore1;
            btn_score = mBtnScore1;
        } else if (i == R.id.btn_score2) {
            score = 2;
            tv_score = mTvScore2;
            btn_score = mBtnScore2;
        } else if (i == R.id.btn_score3) {
            score = 3;
            tv_score = mTvScore3;
            btn_score = mBtnScore3;
        } else if (i == R.id.btn_score4) {
            score = 4;
            tv_score = mTvScore4;
            btn_score = mBtnScore4;
        } else if (i == R.id.btn_score5) {
            score = 5;
            tv_score = mTvScore5;
            btn_score = mBtnScore5;
        }
        if (ObjectUtils.isNotEmpty(tv_score)) {
            tv_score.setSelected(true);
        }
        if (ObjectUtils.isNotEmpty(btn_score)) {
            btn_score.setSelected(true);
        }
    }
}
